/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.serialization.json;

import com.aduib.boot.common.SPI.SPILoader;
import com.aduib.boot.common.json.JsonParser;
import com.aduib.boot.common.serialization.api.ObjectWriter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @description: JsonObjectWriter
 * @author: zzh
 * @date: 2021/10/13 15:20
 */
public class JsonObjectWriter implements ObjectWriter {

    private final PrintWriter writer;

    private JsonParser jsonParser;

    public JsonObjectWriter(OutputStream outStream) {
        this.writer = new PrintWriter(new OutputStreamWriter(outStream));
        this.jsonParser= SPILoader.INSTANCE.getAdaptiveSPI(JsonParser.class);
    }

    @Override
    public void writeObject(Object v) throws IOException {
        String jsonString = jsonParser.write(v);
        writer.write(jsonString);
        writer.println();
        writer.flush();
    }

    @Override
    public void writeBoolean(boolean v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeByte(byte v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeBytes(byte[] v) throws IOException {
        writer.write(new String(v,StandardCharsets.UTF_8));
    }

    @Override
    public void writeBytes(byte[] v, int off, int len) throws IOException {
        writer.write(new String(v, StandardCharsets.UTF_8),off,len);
    }

    @Override
    public void writeShort(short v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeInt(int v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeLong(long v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeFloat(float v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeDouble(double v) throws IOException {
        writeObject(v);
    }

    @Override
    public void writeUtfString(String v) throws IOException {
        writeObject(v);
    }

    @Override
    public void flushBuffer() throws IOException {
        writer.flush();
    }
}
